<template>
  <div id="PermissionDetail">
    <div class="container">
      <div class="table-wrap">
        <div class="table-right">
          <div class="group-item">
            <a-form-model
              ref="form"
              :model="form"
              :rules="rules"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 14 }"
            >
              <div class="form-row">
                <a-form-model-item label="角色名称" prop="name" class="form-col">
                  <a-input
                    v-model="form.roleName"
                    placeholder="请输入角色名称"
                  />
                </a-form-model-item>
                <a-form-model-item label="角色编码" prop="roleCode" class="form-col">
                  <a-input
                    v-model="form.roleCode"
                    placeholder="请输入角色编码"
                  />
                </a-form-model-item>
                <a-form-model-item label="状态" prop="status" class="form-col">
                  <a-radio-group v-model="form.roleStatus">
                    <a-radio :value="true"> 启用 </a-radio>
                    <a-radio :value="false"> 禁用 </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </div>
            </a-form-model>
          </div>
          <div class="group-item">
            <div class="group-top">
              <span class="title" style="font-size: 16px">菜单权限</span>
            </div>
            <a-tabs :default-active-key="activeName">
              <a-tab-pane
                v-for="(item, index) in menuList"
                :key="index"
                :name="index + ''"
                :tab="item.powerName"
              >
                <Cascader
                  :props="{
                    label: 'powerName',
                    children: 'sub_power',
                    checked: 'showMenu'
                  }"
                  :data="item"
                />
              </a-tab-pane>
            </a-tabs>
          </div>
          <div style="margin-bottom: 20px;">
            <div style="margin-bottom: 10px;">项目数据权限</div>
            <div>
              <a-radio-group v-model="projectAccess">
                <a-radio value="PART"> 负责项目权限 </a-radio>
                <a-radio value="ALL"> 全部项目权限 </a-radio>
              </a-radio-group>
            </div>
          </div>
          <div style="margin-bottom: 20px;">
            <div style="margin-bottom: 10px;">请购部门权限</div>
            <div>
              <a-radio-group v-model="deptAccess">
                <a-radio value="PART"> 负责请购部门权限 </a-radio>
                <a-radio value="ALL"> 全部请购部门权限 </a-radio>
              </a-radio-group>
            </div>
          </div>
          <a-button type="primary" @click="changePermissions">保存</a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import util from '@/util/util'

@Component
export default class PermissionDetail extends Vue {
  loading: boolean = true
  menuList: any[] = []
  checks: any = {}
  data: any = {}
  projectAccess:any = 'PART'
  deptAccess:any = 'PART'
  activeName: any = '0'
  form: any = {
    roleName: '',
    roleCode: '',
    roleStatus: true
  }
  rules: any = {
    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    roleStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
    roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
  };

  get roleId () {
    return this.$route.query.roleId || ''
  }
  get name () {
    return this.$route.query.name
  }

  init () {
    this.getMenuList()
    this.roleId && this.getDetail()
  }
  getDetail () {
    let data = {
      roleId: this.roleId
    }
    this.$api.adminRoleDetailFetch(data).then((res: any) => {
      if (res.data.roleStatus == 1) {
          res.data.roleStatus = true
      } else {
        res.data.roleStatus = false
      }
      this.projectAccess = res.data.projectAccess ? res.data.projectAccess : 'PART'
      this.deptAccess = res.data.deptAccess ? res.data.deptAccess : 'PART'
      let { roleName, roleCode, roleStatus } = res.data
      Object.assign(this.form, {
        roleName,
        roleCode,
        roleStatus
      })
    })
  }
  // 角色权限列表
  async getMenuList () {
    const res = await this.$api.adminRolePowerListFetch({ roleId: this.roleId })
    this.menuList = res.data
    // this.initValue()
    this.activeName = '0'
    this.loading = false
  }
  initValue () {
    this.checks = {}
    this.menuList.forEach((item) => {
      this.checks[item.powerId] = []
      item.sub_power &&
        item.sub_power.forEach((child: any) => {
          child.show_menu &&
            child.sub_power &&
            child.sub_power.forEach((sub: any) => {
              sub.show_menu &&
                !sub.sub_power &&
                this.checks[item.powerId].push([child.powerId, sub.powerId])
              sub.show_menu &&
                sub.sub_power &&
                sub.sub_power.forEach((power: any) => {
                  power.show_menu &&
                    this.checks[item.powerId].push([
                      child.powerId,
                      sub.powerId,
                      power.powerId
                    ])
                })
            })
        })
    })
  }
  // 修改权限
  changePermissions () {
    let userInfo: any = JSON.parse(localStorage.getItem('userInfo') as string)
    let powerIds = this.$util
      .flatten(this.menuList, 'sub_power')
      .filter((item: any) => item.showMenu)
      .map((item: any) => item.powerId)
    if (!powerIds.length) {
      return this.$message.error('至少勾选一项权限')
    }
    let data = Object.assign(this.form, {
      roleId: this.roleId
    })
    if (data.roleStatus) {
      data.roleStatus = 1
    } else {
      data.roleStatus = 0
    }
    data.projectAccess = this.projectAccess
    data.deptAccess = this.deptAccess
    let apiFetch = this.roleId ? this.$api.adminRoleUpdateRoleFetch : this.$api.adminRoleAddRoleFetch
    apiFetch(data).then((res: any) => {
      this.updatePermission(res.data, powerIds)
    })
  }
  // 修改角色权限
  updatePermission (roleId: any, powerIds: any) {
    let userInfo: any = JSON.parse(localStorage.getItem('userInfo') as string)
    this.$api.adminRoleUpdatePowerFetch({
        roleId: roleId.roleId,
        powerIds: powerIds.join(',')
      }).then((res: any) => {
        // this.$message.success('修改角色权限成功')
        if (this.roleId === userInfo.roleId) {
          setTimeout(() => {
            this.$message.info('请重新登录')
            localStorage.removeItem('userInfo')
            localStorage.removeItem('sessionId')
            this.$router.replace('/login')
          }, 1000)
        } else {
          this.$router.push({ path: '/systemManage/roleManage' })
        }
      })
  }
}
</script>

<style lang="scss">
#PermissionDetail {
  .table-wrap {
    padding-top: 5px;
    .table-right {
      .group-item {
        margin: 25px 0;
        padding: 0 0px 10px 10px;
        // border-bottom: 1px solid #e7e6eb;
        &::after {
          content: '';
          display: block;
          clear: both;
        }
        .group-top {
          margin: 0 0 15px;
          .edit-btn {
            color: #4b9eed;
            margin: 0 0 0 20px;
            cursor: pointer;
          }
        }
        .group-name {
          color: grey;
        }
        .group-user {
          li {
            float: left;
            background-color: #eee;
            height: 24px;
            line-height: 24px;
            margin: 0 10px 5px 0;
            padding: 0 10px;
          }
        }
        .group-store {
          li {
            width: 100%;
            height: 24px;
            line-height: 24px;
            margin: 0 10px 5px 0;
          }
        }
      }
    }
  }
}
.form-row {
  display: flex;
  flex-wrap: wrap;
  .form-col {
    width: 50%;
    flex-shrink: 0;
  }
}
</style>
